<?php

namespace app\admin\controller;

use app\common\lib\user_operate\UserOperate as UO;
use cmf\controller\AdminBaseController;
use plugins\contract\contract_template\Config;
use think\Db;

class PublicController extends AdminBaseController
{

    public function _initialize()
    {

    }

    public function index()
    {
        return $this->login();
    }

    /**
     * 后台登陆界面
     */
    public function login()
    {
        $param = $this->request->param();
        
        // if(isset($param['admin']) && ( empty(Config('admin_sign')) || $param['admin'] == Config('admin_sign'))){
        $this->assign('admin',true);

        $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");
        if (empty($loginAllowed)) {

            //$this->error('非法登录!', cmf_get_root() . '/');
            //$this->error('请重新登录', url('public/logout'));
            session('ADMIN_ID', null);

            session('ADMIN_SUPER', null);
            return $this->fetch(":login");
            //redirect(url("/"));
            //echo show_message( 0, '非法登录' , '非法操作' , url('public/logout') );exit;

        }

        $admin_id = session('ADMIN_ID');

        $admin_super = session('ADMIN_SUPER');

        if (!empty($admin_id) && !empty($admin_super) && $admin_super == \think\Config::get('super_login')) {
            //已经登录

            redirect(url("admin/Index/index"));

        } else {

            $site_admin_url_password = config("cmf_SITE_ADMIN_URL_PASSWORD");

            $upw = session("__CMF_UPW__");

            if (!empty($site_admin_url_password) && $upw != $site_admin_url_password) {

                redirect(ROOT_PATH . "/");

            } else {

                session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__", true);

                $result = hook_one('admin_login');

                if (!empty($result)) {

                    return $result;

                }

                return $this->fetch(":login");

            }

        }

    }

    /**

     * 登录验证

     */

    public function doLogin()
    {
        $param = $this->request->param();

        $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");
        if (empty($loginAllowed)) {

            // return api_json_echo(false, '非法登录!', null, 111, '/');
    
            //$this->error(, cmf_get_root() . '/');

        }

        $captcha = $this->request->param('captcha');

        if (empty($captcha)) {

            return api_json_echo(false, '验证码不能为空!', null, 102);

            //$this->error(lang('CAPTCHA_REQUIRED'));

        }

        //验证码

        if (!cmf_captcha_check($captcha)) {

            return api_json_echo(false, '验证码错误!', null, 103);

            //$this->error(lang('CAPTCHA_NOT_RIGHT'));

        }

        $name = $this->request->param("username");

        if (empty($name)) {

            return api_json_echo(false, '用户名不能为空!', null, 104);

            //$this->error(lang('USERNAME_OR_EMAIL_EMPTY'));

        }

        $pass = $this->request->param("password");

        if (empty($pass)) {

            return api_json_echo(false, '密码不能为空!', null, 105);

            //$this->error(lang('PASSWORD_REQUIRED'));

        }

        if (strpos($name, "@") > 0) {
            //邮箱登陆

            $where['user_email'] = $name;

        } else {

            $where['user_login'] = $name;

        }

        $result = Db::name('user')->where($where)->find();

        if (false || !empty($result) && $result['user_type'] == 1) {

            if (cmf_compare_password($pass, $result['user_pass'])) {
                $groups = Db::name('user_attach')

                    ->alias("a")

                    ->join('role b', 'a.role_id =b.id', 'LEFT')

                    ->where(["a.user_id" => $result["id"], "b.status" => 1])

                    ->value("a.role_id");

                if ((empty($groups) || empty($result['user_status']))) {

                    // $this->error(lang('USE_DISABLED'));

                    return api_json_echo(false, '账号已被停用', null, 106);

                    //$this->error('账户已被停用！');

                }

                if ($result['user_status'] == 3) {

                    return api_json_echo(false, '申请账号未被通过', null, 107);

                    //$this->error('申请账号未被通过！');

                }

                if ($result['user_status'] == 2) {

                    return api_json_echo(false, '申请账号正在审核中，请等待', null, 108);

                    //$this->error('申请账号正在审核中，请等待！');

                }

                //登入成功页面跳转

                session('ADMIN_ID', $result["id"]);

                session('ADMIN_SUPER', \think\Config::get('super_login'));

                session('name', $result["user_login"]);

                $result['last_login_ip'] = get_client_ip(0, true);

                $result['last_login_time'] = time();

                $token = cmf_generate_user_token($result["id"], 'web');

                if (!empty($token)) {

                    session('token', $token);

                }

                Db::name('user')->update($result);

                cookie("admin_username", $name, 3600 * 24 * 30);

                session("__LOGIN_BY_CMF_ADMIN_PW__", null);

                return api_json_echo(true, '登录成功', null, 200, url("admin/Index/index"));

                //$this->success(lang('LOGIN_SUCCESS'), url("admin/Index/index"));

            } else {

                return api_json_echo(false, '密码错误', null, 109);

                //$this->error(lang('PASSWORD_NOT_RIGHT'));

            }

        } else {

            $company = Db::name('company')->column('company_id');

            if (empty($company)) {

                $data['username'] = \think\Config::get('super_login');

                if ($data['username'] != $name) {

                    return api_json_echo(false, '账号不存在！', null, 110);

                    //$this->error('账号不存在！');

                }

                $data['password'] = $this->request->param('password');

                $uo = new UO();

                try {

                    $res = $uo->activation($data['username'], $data['password']);

                } catch (\Exception $e) {

                    // throw new \Exception($e->getMessage());

                    //获取异常信息

                    return api_json_echo(false, '异常:' . $e->getMessage(), null, 111);

                }

                if ($res['status'] == 'error') {

                    return api_json_echo(false, $res['message'] . ',code:' . $res['code'], null, 120);

                    //$this->error( $res['message'] . ',code:'.$res[ 'code' ] );

                }

                if (!isset($res['data'])) {

                    return api_json_echo(true, '未获取到相关数据，激活账号失败，请联系管理员', null, 121);

                    //$this->error('未获取到相关数据，激活账号失败，请联系管理员！');

                }

                $this->clearTable('202004241713');

                //保存数据

                $res = $this->saveData($res['data']);

                if ($res) {

                    try {

                        $active = $uo->activeSuccess($data['username'], $data['password']);

                    } catch (\Exception $e) {

                        //获取异常信息

                        return api_json_echo(false, '异常:' . $e->getMessage(), null, 122);

                    }

                    if ($active['status'] == 'error') {

                        //数据保存失败，清空表数据

                        $this->clearTable('202004241713');

                        return api_json_echo(false, $active['message'] . ' ,code:' . $active['code'], null, 123);

                        //$this->error(  $active[ 'message' ].' ,code:'.$active[ 'code' ] );

                    }

                    return api_json_echo(true, '账号激活成功，请重新登录', null, 200, url('public/login'));

                    //$this->success('账号激活成功，请重新登录！',url('public/login'));

                } else {

                    //数据保存失败，清空表数据

                    $this->clearTable('202004241713');

                    return api_json_echo(false, '获取账号信息失败，请联系管理员', null, 125);

                    //$this->error('获取账户信息失败，请联系管理员！');

                }

                //$this->success('登录成功！',url("admin/Index/index"));

            } else {

                return api_json_echo(false, '账号不正确，请检查', null, 126);

                //$this->error('账号不正确，请检查！');

            }

            //   $this->error(lang('USERNAME_NOT_EXIST'));

        }

    }

    /**

     * [saveData description]

     * @param  [type] $data [description]

     * @return [type]       [description]

     */

    protected function saveData($data)
    {

        $isOk = true;

        Db::startTrans();

        try {

            $data['user']['employee_id'] = '10001001';

            $data['user']['user_login'] = 'admin';

            $userId = Db::name('user')->insertGetId($data['user']);

            $data['company']['super_admin'] = $userId;

            $data['company']['super_login'] = \think\Config::get('super_login');

            $data['company']['id'] = 1;

            $companyId = Db::name('company')->insertGetId($data['company']);

            //添加角色 部门

            $department['status'] = 1;

            $department['parent_id'] = 0;

            $department['department_NO'] = '10';

            $department['name'] = '办公室';

            $department['remark'] = '办公室';

            $department['company_id'] = $companyId;

            $departmentId = Db::name('department')->insertGetId($department);

            $role['parent_id'] = 0;

            $role['department_id'] = $departmentId;

            $role['status'] = 1;

            $role['create_time'] = time();

            $role['name'] = 'CEO';

            $role['remark'] = 'CEO';

            $role['company_id'] = $companyId;

            $roleId = Db::name('role')->insertGetId($role);

            $attach['user_id'] = $userId;

            $attach['role_id'] = $roleId;

            $attach['department_id'] = $departmentId;

            $attach['company_id'] = $companyId;

            Db::name('user_attach')->insert($attach);

            // 提交事务

            Db::commit();

        } catch (\Exception $e) {

            $isOk = false;

            // 回滚事务

            Db::rollback();

        }

        return $isOk;

    }

    /**

     * 后台管理员退出

     */

    public function logout()
    {

        $param =[ 'code'=> 200 , 'msg' => '退出成功'];
        \think\Hook::listen( 'response_resulut' , $param  );
        
        session('ADMIN_ID', null);

        session('ADMIN_SUPER', null);

        $adminMenu = new \app\admin\model\AdminMenuModel();

        $adminMenu->clearCacheMenu();

        return redirect(url('public/login', [], false, true));
        // return redirect(url('/', [], false, true));
    }



    /**

     * 清空表数据

     */

    public function clearTable($pwd)
    {

        if ($pwd == '202004241713') {

            $table = ['cmf_user', 'cmf_company', 'cmf_role', 'cmf_user_attach', 'cmf_department', 'cmf_auth_access'];

            foreach ($table as $key => $value) {

                $res = Db::execute('truncate table ' . $table[$key]);

            }

        }

    }

    // //商店登陆界面
    // public function login_member()
    // {

    //     $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");

    //     if (empty($loginAllowed)) {

    //         //$this->error('非法登录!', cmf_get_root() . '/');

    //         // $this->error('非法登录', url('public/logout_member'));

    //         //echo show_message( 0, '非法登录' , '非法操作' , url('public/logout') );exit;

    //     }

    //     $admin_id = session('ADMIN_ID');

    //     $admin_super = session('ADMIN_SUPER');

    //     if (!empty($admin_id) && !empty($admin_super) && $admin_super == \think\Config::get('super_login')) {
    //         //已经登录

    //         redirect(url("admin/Index/index"));

    //     } else {

    //         $site_admin_url_password = config("cmf_SITE_ADMIN_URL_PASSWORD");

    //         $upw = session("__CMF_UPW__");

    //         if (!empty($site_admin_url_password) && $upw != $site_admin_url_password) {

    //             redirect(ROOT_PATH . "/");

    //         } else {

    //             session("__SP_ADMIN_LOGIN_PAGE_SHOWED_SUCCESS__", true);

    //             $result = hook_one('admin_login');

    //             if (!empty($result)) {

    //                 return $result;

    //             }

    //             return $this->fetch(":login_member");

    //         }

    //     }

    // }

    //商店登陆操作
    public function doLogin_member()
    {

        $loginAllowed = session("__LOGIN_BY_CMF_ADMIN_PW__");

        if (empty($loginAllowed)) {
            // return api_json_echo(false, '非法登录!', null, 101, cmf_get_root() . '/');
            //$this->error(, cmf_get_root() . '/');
        }

        $captcha = $this->request->param('captcha');

        if (empty($captcha)) {

            return api_json_echo(false, '验证码不能为空!', null, 102);

            //$this->error(lang('CAPTCHA_REQUIRED'));

        }

        //验证码

        if (!cmf_captcha_check($captcha)) {

            return api_json_echo(false, '验证码错误!', null, 103);

            //$this->error(lang('CAPTCHA_NOT_RIGHT'));

        }

        $name = $this->request->param("username");

        if (empty($name)) {

            return api_json_echo(false, '用户名不能为空!', null, 104);

            //$this->error(lang('USERNAME_OR_EMAIL_EMPTY'));

        }

        $pass = $this->request->param("password");

        if (empty($pass)) {

            return api_json_echo(false, '密码不能为空!', null, 105);

            //$this->error(lang('PASSWORD_REQUIRED'));

        }

        if (strpos($name, "@") > 0) {
			//邮箱登陆
            $where['user_email'] = $name;

        } else {

            $where['user_login'] = $name;

        }

        $result = Db::name('user')->where($where)->find();

        if (false || !empty($result) && $result['user_type'] == 3) {

            if (cmf_compare_password($pass, $result['user_pass'])) {

                $groups = Db::name('user_attach')

                    ->alias("a")

                    ->join('role b', 'a.role_id =b.id', 'LEFT')

                    ->where(["a.user_id" => $result["id"], "b.status" => 1])

                    ->value("a.role_id");

                // if ((empty($groups) || empty($result['user_status']))) {

                //     // $this->error(lang('USE_DISABLED'));

                //     return api_json_echo(false, '账号已被停用', null, 106);

                //     //$this->error('账户已被停用！');

                // }

                if ($result['user_status'] == 3) {

                    return api_json_echo(false, '申请账号未被通过', null, 107);

                    //$this->error('申请账号未被通过！');

                }

                if ($result['user_status'] == 2) {

                    return api_json_echo(false, '申请账号正在审核中，请等待', null, 108);

                    //$this->error('申请账号正在审核中，请等待！');

                }

                //登入成功页面跳转

                session('ADMIN_ID', $result["id"]);

                session('ADMIN_SUPER', \think\Config::get('super_login'));

                session('name', $result["user_login"]);

                $result['last_login_ip'] = get_client_ip(0, true);

                $result['last_login_time'] = time();

                $token = cmf_generate_user_token($result["id"], 'web');

                if (!empty($token)) {

                    session('token', $token);

                }

                Db::name('user')->update($result);

                cookie("admin_username", $name, 3600 * 24 * 30);

                session("__LOGIN_BY_CMF_ADMIN_PW__", null);
                
                //刷新权限
                if( class_exists( '\\plugins\\store\\Common' ) ){
                    \plugins\store\Common::refreshAuthInfo();
                }
                return api_json_echo(true, '登录成功', null, 200, url("admin/Index/index"));

                //$this->success(lang('LOGIN_SUCCESS'), url("admin/Index/index"));

            } else {

                return api_json_echo(false, '密码错误', null, 109);

                //$this->error(lang('PASSWORD_NOT_RIGHT'));

            }

        } else {

            $company = Db::name('company')->column('company_id');

            if (empty($company)) {

                $data['username'] = \think\Config::get('super_login');

                if ($data['username'] != $name) {

                    return api_json_echo(false, '账号不存在！', null, 110);

                    //$this->error('账号不存在！');

                }

                $data['password'] = $this->request->param('password');

                $uo = new UO();

                try {

                    $res = $uo->activation($data['username'], $data['password']);

                } catch (\Exception $e) {

                    // throw new \Exception($e->getMessage());

                    //获取异常信息

                    return api_json_echo(false, '异常:' . $e->getMessage(), null, 111);

                }

                if ($res['status'] == 'error') {

                    return api_json_echo(false, $res['message'] . ',code:' . $res['code'], null, 120);

                    //$this->error( $res['message'] . ',code:'.$res[ 'code' ] );

                }

                if (!isset($res['data'])) {

                    return api_json_echo(true, '未获取到相关数据，激活账号失败，请联系管理员', null, 121);

                    //$this->error('未获取到相关数据，激活账号失败，请联系管理员！');

                }

                $this->clearTable('202004241713');

                //保存数据

                $res = $this->saveData($res['data']);

                if ($res) {

                    try {

                        $active = $uo->activeSuccess($data['username'], $data['password']);

                    } catch (\Exception $e) {

                        //获取异常信息

                        return api_json_echo(false, '异常:' . $e->getMessage(), null, 122);

                    }

                    if ($active['status'] == 'error') {

                        //数据保存失败，清空表数据

                        $this->clearTable('202004241713');

                        return api_json_echo(false, $active['message'] . ' ,code:' . $active['code'], null, 123);

                        //$this->error(  $active[ 'message' ].' ,code:'.$active[ 'code' ] );

                    }

                    return api_json_echo(true, '账号激活成功，请重新登录', null, 200, url('public/login'));

                    //$this->success('账号激活成功，请重新登录！',url('public/login'));

                } else {

                    //数据保存失败，清空表数据

                    $this->clearTable('202004241713');

                    return api_json_echo(false, '获取账号信息失败，请联系管理员', null, 125);

                    //$this->error('获取账户信息失败，请联系管理员！');

                }

                //$this->success('登录成功！',url("admin/Index/index"));

            } else {

                return api_json_echo(false, '账号不正确，请检查', null, 126);

                //$this->error('账号不正确，请检查！');

            }

            //   $this->error(lang('USERNAME_NOT_EXIST'));

        }


    }

    // /**
    //  * 后台商户退出
    //  */
    // public function logout_member()
    // {
    //     session('ADMIN_ID', null);

    //     session('ADMIN_SUPER', null);

    //     $adminMenu = new \app\admin\model\AdminMenuModel();

    //     $adminMenu->clearCacheMenu();

    //     return redirect(url('/admin/public/login_member.html', [], false, true));

    // }


}
